//
//  MeInfoViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/15.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "MeInfoViewController.h"
#import "MineMainListTableViewCell.h"
#import "UserRes.h"
#import "EDMyEditInfoViewController.h"
#import  "CustomImagePickUtility.h"
#import "MeModifyPWViewController.h"
#import "CustomPickerView.h"
@interface MeInfoViewController()
@property  (nonatomic, strong) NSArray *listAry;
@property (nonatomic, strong) UserRes *user;
@property (nonatomic, strong) NSString *sex;
@property (nonatomic, strong) NSString *dateString;
@end
@implementation MeInfoViewController


- (void)viewDidLoad
{
     [super viewDidLoad];
    self.title = @"个人信息";
    self.user = [CommonMethod getUser];
    if (!self.user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    [self fetchDataWithNet];
    
}

- (void)fetchDataWithNet
{
    
    //更新头像
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"USERNAME"],
                            
                             @"USERNAME":self.user.mobile
                          
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_22 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        NSDictionary  *result  = [response objectForKey:@"info"];
        if ([result.allKeys containsObject:@"DQ0000"]) {
            self.user.USER.DQ0000  = [result  objectForKey:@"DQ0000"];
        }
        
        if ([result.allKeys containsObject:@"CSRQ00"]) {
            self.user.USER.CSRQ00  = [result  objectForKey:@"CSRQ00"];
        }
        if ([result.allKeys containsObject:@"HY0000"]) {
            self.user.USER.HY0000  = [result  objectForKey:@"HY0000"];
        }
        if ([result.allKeys containsObject:@"XB0000"]) {
            self.user.USER.XB0000  = [result  objectForKey:@"XB0000"];
        }
        if ([result.allKeys containsObject:@"NAME00"]) {
            self.user.USER.NAME00  = [result  objectForKey:@"NAME00"];
        }
        [CommonMethod saveUser:self.user];
        [self.mainTableView reloadData];
        
//        self.user.USER.PHOTO1 = APPEND_URL(BASE_URL,[result objectForKey:@"tplj"]);
//        [CommonMethod saveUser:self.user];
//
//        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
//        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}


- (void)updateInfo
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[CommonMethod createMD5Key:@"USERNAME"] forKey:@"FKEY"];
    [params setObject:self.user.mobile forKey:@"USERNAME"];
    if (![CommonMethod isBlankString:self.sex]) {
        [params setObject:self.sex forKey:@"XB0000"];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_23 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        if (![CommonMethod isBlankString:self.sex]) {
            self.user.USER.XB0000 = self.sex;
            [CommonMethod saveUser:self.user];
        
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
            MineMainListTableViewCell *cell =(MineMainListTableViewCell *)[self.mainTableView cellForRowAtIndexPath:indexPath];
            cell.detailLab.text = self.sex;
            self.sex = @"";
        }
        dispatch_async(dispatch_get_main_queue(), ^{
             [SVProgressHUD showInfoWithStatus:@"更新成功"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
      
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}


- (void)handleOutAction:(id)sender
{
    [CommonMethod saveUser:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_Fresh_Userinfo object:nil];
    
}

#pragma mark ----UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    switch (section) {
        case 0:
        {
            return self.listAry.count - 1;
        }
            break;
        case 1:
        {
            return 1;
        }
            break;
            
        default:
            return 0;
            break;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *header = [[UIView alloc]init];
        header.backgroundColor = self.view.backgroundColor;
        return header;
    }
    return nil;
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
            return 15;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 100;
        }
        return 45;
    } else {
        return 45;
        
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    if (section == 1) {
        UIView *footView = [[UIView alloc] init];
        
        footView.backgroundColor = self.view.backgroundColor;
        footView.frame = CGRectMake(0, 0, self.view.frame.size.width, 100);
        
        
        UIButton  *looutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        looutBtn.frame = CGRectMake(15, 40, BOUNDWIDTH - 30, 45);
        [looutBtn setTitle:@"注销登录" forState:UIControlStateNormal];
        looutBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        looutBtn.backgroundColor = RGB(254, 218, 60);
        looutBtn.layer.cornerRadius = 10;
        looutBtn.layer.masksToBounds = YES;
        [looutBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
        [looutBtn addTarget:self action:@selector(handleOutAction:) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:looutBtn];
        
        
        
        return footView;
    }
    return nil;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
           return 100;
    }
 
    return 0;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MineMainListTableViewCell *cell = [MineMainListTableViewCell initWithStyWithImgleWithTab:tableView andreuseIdentifier:@"MineMainListTableViewCellWithImg"];
            cell.textLab.text = self.listAry[0];
            //        NSLog(@"url%@",kAPIBaseImage(self.user.loginName));
            
            [cell.headerImgv sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, self.user.USER.PHOTO1)] placeholderImage:[UIImage imageNamed:@"headImage"]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            //        cell.tag = CELLTAG + indexPath.row;
            return cell;
        }
        
        MineMainListTableViewCell *cell = [MineMainListTableViewCell initWithStyleWithTab:tableView andreuseIdentifier:@"MineMainListTableViewCell"];
        cell.textLab.text = self.listAry[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //    cell.tag = CELLTAG + indexPath.row;
        switch (indexPath.row) {
            case 1:
            {
                //昵称
                cell.arrowImgv.hidden = NO;
                cell.detailLab.text = self.user.USER.NICK00;
                
            }
                break;
            case 2:
            {
                //性别
                cell.arrowImgv.hidden = NO;
                cell.detailLab.text = self.user.USER.XB0000;
                
            }
                break;
            case 3:
            {
                //生日
                cell.arrowImgv.hidden = NO;
                cell.detailLab.text = self.user.USER.CSRQ00;
                
            }
                break;
            case 4:
            {
                //地区
                cell.arrowImgv.hidden = NO;
                cell.detailLab.text = self.user.USER.DQ0000;
                
            }
                break;
            case 5:
            {
                //行业
                cell.detailLab.text = self.user.USER.HY0000;
                cell.arrowImgv.hidden = NO;
                
            }
                break;
          
                
            default:
                break;
        }
        
        return cell;
    } else {
        
        MineMainListTableViewCell *cell = [MineMainListTableViewCell initWithStyleWithTab:tableView andreuseIdentifier:@"MineMainListTableViewCell"];
        cell.textLab.text = self.listAry.lastObject;
         cell.arrowImgv.hidden = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section  == 0) {
        switch (indexPath.row) {
            case 0:
            {
                [CustomImagePickUtility showSheet:self andTitle:@"选择图片" andImageCount:1 WithEditCamera:YES];

                
            }
                break;
            case 1:
            {
                //昵称
                EDMyEditInfoViewController  *control = [[EDMyEditInfoViewController alloc] init
                                                        ];
                control.type = 1;
                control.editCallBack = ^(NSString * _Nonnull result) {
                    self.user.USER.NICK00 = result;
                    [CommonMethod saveUser:self.user];
                    
//                    self.loginAccount = result;
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                    MineMainListTableViewCell *cell =(MineMainListTableViewCell *)[self.mainTableView cellForRowAtIndexPath:indexPath];
                    cell.detailLab.text = result;
                     [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_Fresh_Userinfo object:nil];
                 
                };
                [self.navigationController pushViewController:control animated:YES];
                
            }
                break;
            case 2:
            {
                
                [UIActionSheet showInView:self.view withTitle:@"选择性别" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"男",@"女"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
                    NSLog(@"index%ld",buttonIndex);
                    switch (buttonIndex) {
                        case 0:
                        {
                            self.sex = @"男";
                        }
                            break;
                        case 1:
                        {
                            self.sex = @"女";
                        }
                            break;
                    
                            
                        default:
                            self.sex = @"";
                            break;
                    }
                    [self updateInfo];
                }];


                
            }
                break;
            case 3:
            {
                //生日
                [CustomPickerView initWithFrame:CGRectZero withModeType:DatePicker andTitleLab:@"请选择时间" componentAry:nil andHasChoose:nil andCallBack:^(id resutData) {
                    NSLog(@"%@",resutData);
                    
                        NSDateFormatter *formatter  = [[NSDateFormatter alloc]init];
                    
                        [formatter setDateFormat:@"yyyy-MM-dd"];
              
                    
//                     NSDate *date=[formatter dateFromString:resutData[@"subscribeTime"]];
                    
                    NSString *currentDateString=[formatter stringFromDate:resutData];

                    
                    
                    
                    //保存信息
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:[CommonMethod createMD5Key:@"USERNAME"] forKey:@"FKEY"];
                    [params setObject:self.user.mobile forKey:@"USERNAME"];
                    [params setObject:currentDateString forKey:@"CSRQ00"];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showWithStatus:nil];
                    });
                    
                    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_23 params:params md5Paraname:nil success:^(id  _Nullable response) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                        });
                        
                        
                        self.user.USER.CSRQ00 = currentDateString;
                        [CommonMethod saveUser:self.user];
                        
                        //                    self.loginAccount = result;
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
                        MineMainListTableViewCell *cell =(MineMainListTableViewCell *)[self.mainTableView cellForRowAtIndexPath:indexPath];
                        cell.detailLab.text = currentDateString;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [SVProgressHUD showInfoWithStatus:@"更新成功"];
                            //                [SVProgressHUD dismissWithDelay:10];
                        });
                        
                    } fail:^(NSError * _Nonnull error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                        });
                        
                    }];
                    
                    
                    
                    
                  
                    
//
                }];
                
            }
                break;
            case 4:
            {
               //地区
                                EDMyEditInfoViewController  *control = [[EDMyEditInfoViewController alloc] init
                                                                        ];
                                control.type = 2;
                                control.editCallBack = ^(NSString * _Nonnull result) {
                                    self.user.USER.DQ0000 = result;
                                    [CommonMethod saveUser:self.user];
                
                                    //                    self.loginAccount = result;
                                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:4 inSection:0];
                                    MineMainListTableViewCell *cell =(MineMainListTableViewCell *)[self.mainTableView cellForRowAtIndexPath:indexPath];
                                    cell.detailLab.text = result;
                                    
                                };
                                [self.navigationController pushViewController:control animated:YES];
                
            }
                break;
            case 5:
            {
                //行业
                                EDMyEditInfoViewController  *control = [[EDMyEditInfoViewController alloc] init
                                                                        ];
                                control.type = 3;
                                control.editCallBack = ^(NSString * _Nonnull result) {
                                    self.user.USER.HY0000 = result;
                                    [CommonMethod saveUser:self.user];
                
                                    //                    self.loginAccount = result;
                                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:5 inSection:0];
                                    MineMainListTableViewCell *cell =(MineMainListTableViewCell *)[self.mainTableView cellForRowAtIndexPath:indexPath];
                                    cell.detailLab.text = result;
                                   
                                };
                                [self.navigationController pushViewController:control animated:YES];
                
            }
                break;

                
            default:
                break;
        }
        
    } else {
        
        MeModifyPWViewController *controller = [[MeModifyPWViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }

    
    
}

#pragma mark -------------CustomImagePickUtilityDelegate
- (void)pickPhotoWithImage:(NSArray *)imgsAry{
    
    if (imgsAry.count ==0) {
        return;
    }
    
    
    UIImage *uploadImage  =  imgsAry[0];
    NSData *data = UIImageJPEGRepresentation(uploadImage, 0.3);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //    UIImage *resultImage = [UIImage imageWithData:data];
    
    //更新头像
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"TOKEN":self.user.TOKEN,
                             @"USERNAME":self.user.mobile,
                             @"HZM000":@"jpg",
                             @"IMGSTR":encodedImageStr
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_21 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        NSDictionary  *result  = response;
        
        self.user.USER.PHOTO1 = [result objectForKey:@"tplj"];
        [CommonMethod saveUser:self.user];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"更新成功"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_Fresh_Userinfo object:nil];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
//    [_EDProgressHUD showHUDWithStyle:EDProgressHUDStyleLoading superview:self.view alertMsg:kNetLoading];
//    
//    UIImage *uploadImage  =  imgsAry[0];
//    NSData *data = UIImageJPEGRepresentation(uploadImage, 0.3);
//    UIImage *resultImage = [UIImage imageWithData:data];
//    [[EDNet sharedInstance]uploadImg:uploadImage completionHandler:^(NSURLResponse *response, EDResponseModel *responseObject, NSError *error) {
//        if (responseObject.isSucceed) {
//            [_EDProgressHUD hideForSuperview:self.view];
//            self.imageUrl = responseObject.resultModel;
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//            MineMainListTableViewCell *cell =(MineMainListTableViewCell *)[self.tableview  cellForRowAtIndexPath:indexPath];
//            [cell.headerImgv setImage:uploadImage];
//            
//            
//            //            [[EDNet sharedInstance]
//            //             fetchAppCodeWithCompletionHandler:^(NSURLResponse *response, EDResponseModel *model, NSError *error) {
//            //                 self.code = model.resultModel;
//            //
//            //                 [self fetchAccessToken];
//            //             }];
//            
//            //            obj.state = Custom_Upload_State_Success;
//            //            obj.uploadImgUrl = responseObject.resultModel;
//            //            obj.progress = 1;
//            //
//            //            count ++;
//            //            uploadImgOver(YES);
//        }else{
//            [_EDProgressHUD showHUDWithStyle:EDProgressHUDStyleError superview:self.view alertMsg:responseObject.msg];
//            
//            //            obj.state = Custom_Upload_State_Fail;
//            //            count ++;
//            //            uploadImgOver(NO);
//        }
//    }];
    
    
    //    UIImage *img = [imgsAry firstObject];
    //    if (img != nil) {
    //        @weakify(self);
    //        [[Bx_QiniuUploadManager shareInstance]qiniuUpLoadWithImg:img andProgress:^(float percent) {
    //
    //        } andSuccess:^(id suc) {
    //            @strongify(self);
    //            [self.viewmodel.raccommand execute:@{
    //                                                 @"params":@{@"head_img":suc},
    //                                                 @"url":Bx_API_MyInfoEdit
    //                                                 }];
    //        } andFail:^(id error) {
    //            dispatch_async(dispatch_get_main_queue(), ^{
    //                [SVProgressHUD showErrorWithStatus:error];
    //                [SVProgressHUD dismissWithDelay:1.35];
    //            });
    //        }];
    //    }
}




- (NSArray *)listAry {
    if (!_listAry) {
        _listAry = @[@"头像",@"昵称",@"性别",@"生日",@"地区",@"行业",@"修改密码"];
    }
    return _listAry;
    
}

@end
